//
//  NewAddressViewController.m
//  GoBigMarket
//
//  Created by 王天义 on 16/8/17.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "NewAddressViewController.h"
#import "NewAddressTableViewCell.h"
#import "NewAddressModel.h"
#import "AddMapViewController.h"
@interface NewAddressViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,BMKGeoCodeSearchDelegate,trunDelegaet>
{
    
    /**
     *  联系人姓名
     */
    NSString *ShipTo;
    /**
     *  联系人姓名
     */
    NSInteger Id;
    /**
     *  联系人电话
     */
    NSString *Phone;
    /**
     *  地址1
     */
    NSString *Addr1;
    /**
     *  地址2
     */
    NSString *Addr2;
    /**
     *  拼接后的地址
     */
    NSString *Address;
    /**
     *  省份名称
     */
    NSString *Province;
    /**
     *  城市名称
     */
    NSString *City;
    /**
     *  区县名称
     */
    NSString *County;
    /**
     *  街道
     */
    NSString *ShotAddress;
    /**
     *  经度
     */
    NSString *longitude;
    /**
     *  纬度
     */
    NSString *latitude;
    /**
     *  经度
     */
    NSString *longitudeX;
    /**
     *  纬度
     */
    NSString *latitudeY;
    
  
}


//左边Label和每行占位文字显示数组
@property (nonatomic , strong)NSString *longitudeXX;
/**
 *  纬度
 */
@property (nonatomic , strong)NSString *latitudeYY;
/**
 *  区区
 */
@property (nonatomic , strong)NSString *CountyX;
/**
 *  省省
 */
@property (nonatomic , strong)NSString *Provincex;
@property (nonatomic ,strong)NSMutableArray *leftLabelAry;
@property (nonatomic, strong)NSMutableArray *placeholderAry;
@property (nonatomic, strong)NSString *trun;

@end

@implementation NewAddressViewController

#pragma mark --- 数据源懒加载
- (NSMutableArray *)datas{
    if (_datas == nil) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSMutableArray *)leftLabelAry{
    if (_leftLabelAry == nil) {
        _leftLabelAry = [NSMutableArray arrayWithObjects:@"姓名：",@"电话：",@"收货地址:",@"门牌号", nil];
    }
    return _leftLabelAry;
}

- (NSMutableArray *)placeholderAry{
    if (_placeholderAry == nil) {
        _placeholderAry = [NSMutableArray arrayWithObjects:@"请填写收货人姓名",@"请填写收货手机号码",@"小区/写字楼/学校等",@"详细地址（例：16号楼 - 202室）", nil];
    }
    return _placeholderAry;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    _trun = @"0";
    [self ifBianJi];
    [self creatTableView];
    
}
- (void)truneDelgateData{
    _trun = @"1";
}
- (void)ifBianJi{
    
    if (self.isBianJi == YES) {
        self.title = @"编辑收货地址";
        
        NewAddressModel *model = self.datas.lastObject;
        ShipTo = model.ShipTo;
        Phone = model.Phone;
        Addr1 = model.Address;
        Addr2 = model.RoomNum;
        longitude = model.Lng;
        latitude = model.Lat;
        Id = model.Id;
        Province = model.Province;
        City = model.City;
        ShotAddress = model.ShotAddress;
        County = model.County;
    }else{
        self.title = @"新增收货地址";
    }
}
#pragma mark --- 创建视图
- (void)creatTableView{
    
    UITableView *addressView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    addressView.delegate = self;
    addressView.dataSource = self;
    addressView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:addressView];
    
    UIButton *saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, XNWindowHeight - 64 - 50, XNWindowWidth, 50)];
    [saveBtn setTitle:@"确定" forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    saveBtn.backgroundColor = XNColor(1, 196, 92, 1);
    [self.view addSubview:saveBtn];
}

#pragma mark --- tableView数据源代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.leftLabelAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"NewAddressTableViewCellID";
    BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([NewAddressTableViewCell class]) bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
        nibsRegistered = YES;
    }
    NewAddressTableViewCell *newAddressViewCell = (NewAddressTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    newAddressViewCell.homeNewAddressText.delegate = self;
    
    [newAddressViewCell setSelectionStyle:UITableViewCellSelectionStyleNone];
    newAddressViewCell.homeNewAddressLabel.text = self.leftLabelAry[indexPath.row];
    newAddressViewCell.homeNewAddressText.placeholder = self.placeholderAry[indexPath.row];
    newAddressViewCell.homeNewAddressText.tag = 100 + indexPath.row;
    
    switch (indexPath.row) {
        case 0:
            newAddressViewCell.homeNewAddressText.text = ShipTo;
            break;
        case 1:
            newAddressViewCell.homeNewAddressText.text = Phone;
            break;
        case 2:
            newAddressViewCell.homeNewAddressText.text = Addr1;
            newAddressViewCell.homeNewAddressText.enabled = NO;
            
            break;
        case 3:
            newAddressViewCell.homeNewAddressText.text = Addr2;
            break;
            
        default:
            break;
    }
    
    return newAddressViewCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        
        AddMapViewController *vc = [[AddMapViewController alloc] init];
        vc.delegate = self;
        vc.addressBlock = ^(NSDictionary *dic) {
            
            Addr1 = [NSString stringWithFormat:@"%@",[dic objectForKey:@"address"]];// 一串地址
            
            
            City = [NSString stringWithFormat:@"%@",[dic objectForKey:@"city"]];// 城市名称
            
            ShotAddress = [NSString stringWithFormat:@"%@",[dic objectForKey:@"name"]];// 街道
            longitude = [NSString stringWithFormat:@"%@",[dic objectForKey:@"lon"]];// 经度
            latitude = [NSString stringWithFormat:@"%@",[dic objectForKey:@"lat"]];// 纬度
            longitudeX = [NSString stringWithFormat:@"%@",[dic objectForKey:@"locationX"]];// 经度
            latitudeY = [NSString stringWithFormat:@"%@",[dic objectForKey:@"locationY"]];// 经度
            
            [self EnGeocode:longitudeX :latitudeY];
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:YES];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

#pragma mark --- textField代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"\n"]) {
        [self.view endEditing:YES];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (textField.tag == 100) {
        ShipTo = textField.text;
    }else if (textField.tag == 101){
        Phone  = textField.text;
    }else if (textField.tag == 102){
        Addr1 = textField.text;
    }else if (textField.tag == 103){
        Addr2 = textField.text;
    }
}
#pragma mark - 反地理编码
- (void)EnGeocode:(NSString *)XX:(NSString *)latitudeYY {
    //初始化检索对象
    BMKGeoCodeSearch *_geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
    _geoCodeSearch.delegate = self;
    //初始化反地理编码类
    BMKReverseGeoCodeOption *reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    //需要反地理编码的坐标位置
    _latitudeYY = latitudeYY;
    _longitudeXX = XX;
    reverseGeoCodeOption.reverseGeoPoint = CLLocationCoordinate2DMake(XX.doubleValue, latitudeYY.doubleValue);
    // 调用反地址编码方法，让其在代理方法中输出
    BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
    if(flag)
    {
        DLog(@"反geo检索发送成功");
    }
    else
    {
        DLog(@"反geo检索发送失败");
    }
    
    
}
#pragma mark 代理方法返回反地理编码结果
//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:
(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        _Provincex = result.addressDetail.province;
        _CountyX  = result.addressDetail.district;
        Province = [NSString stringWithFormat:@"%@",result.addressDetail.province];// 省份名称
        County = [NSString stringWithFormat:@"%@",result.addressDetail.district];// 区县名称
        DLog(@"=====------===huang%@", result.addressDetail.city);
        DLog(@"=====------===%@", result.addressDetail.district);
        DLog(@"=====------===%@", result.addressDetail.province);
        
        NSString *str = result.businessCircle;
        DLog(@"=========%@",str);
        
    }
    else {
        DLog(@"抱歉，未找到结果");
    }
}
#pragma mark --- 点击保存按钮

- (void)saveBtnClick{
    
    if ([RegularExpressions isBlankString:ShipTo]) {
        [SVProgressHUD  showWithStatus:@"请填写名称"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
    }else if(ShipTo.length > 5){
        [SVProgressHUD  showWithStatus:@"名字最多只能输入五个"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        return;
    }else if([Phone isEqualToString:@""] || ![RegularExpressions validateMobile:Phone]){
        [SVProgressHUD  showWithStatus:@"请正确输入手机号"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        return;
    }else if ([RegularExpressions isBlankString:Addr1]){
        [SVProgressHUD  showWithStatus:@"请选择地址"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        return;
    }else if ([RegularExpressions isBlankString:Addr2]){
        [SVProgressHUD  showWithStatus:@"请填写详细地址"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        
        return;
    }
    else{
        
        if (self.isBianJi == YES) {
            [self editInfoData];
            self.isBianJi = NO;
        }else{
         
            [self saveInfoData];
        }
    }
}

#pragma mark --- 新增保存请求

- (void)saveInfoData{
    NSDictionary *dicStr = @{};
    if ([_trun isEqualToString:@"1"]) {
      dicStr = @{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"Province":_Provincex,@"City":City,@"County":_CountyX,@"Address":Addr1,@"Phone":Phone,@"ShipTo":ShipTo,@"Lng":_latitudeYY,@"Lat":_longitudeXX,@"ShotAddress":ShotAddress,@"RoomNum":Addr2};
    } else{
    dicStr = @{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"Province":Province,@"City":City,@"County":County,@"Address":Addr1,@"Phone":Phone,@"ShipTo":ShipTo,@"Lng":longitude,@"Lat":latitude,@"ShotAddress":ShotAddress,@"RoomNum":Addr2};
    }

    [CQNetWorkTools POSTWithURL:AddShippingAddress par:dicStr success:^(id responseObject) {
        DLog(@"====%@",dicStr);
        DLog(@"===----%@",responseObject);
        if ([[responseObject objectForKey:@"Err"] intValue]) {
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        }else{
            DLog(@"success%@",responseObject);
            [self.navigationController popViewControllerAnimated:YES];
        }
    } filed:^(NSError *error) {
        DLog(@"失败===%@", error);
        [SVProgressHUD  showWithStatus:@"请检查网络"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
    }];
}

#pragma mark --- 编辑保存请求

- (void)editInfoData{
    
    NSDictionary *dicStr = @{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"Province":Province,@"City":City,@"County":County,@"Address":Addr1,@"Phone":Phone,@"ShipTo":ShipTo,@"Lng":longitude,@"Lat":latitude,@"ShotAddress":ShotAddress,@"RoomNum":Addr2,@"Id":[NSNumber numberWithInteger:Id]};
    [CQNetWorkTools POSTWithURL:EditShippingAddress par:dicStr success:^(id responseObject) {
        if ([[responseObject objectForKey:@"Err"]integerValue] != 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[responseObject objectForKey:@"ErrMsg"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:action1];
            [self presentViewController:alert animated:YES completion:^{
                
            }];
        }else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    } filed:^(NSError *error) {
        DLog(@"失败===%@", error);
        [SVProgressHUD  showWithStatus:@"请检查网络"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        
    }];
}


- (void)dismiss{
    [SVProgressHUD dismiss];
}

@end
